<?php
/**
 * Created by PhpStorm.
 * User: xuanbang.wen
 * Date: 2020/2/12
 * Time: 11:11
 */

namespace App\Service\ExternalAPI;


use EchoPHP\Facades\Log;
use GuzzleHttp\Client;
use Exception;

class VSApi {
    //系统类型
    private $systemType;
    //时间戳
    private $timeStamp;
    //
    private $key;
    //接口地址
    private $host;
    //guzzle
    private $client;

    private $timeout;
    //翻译视频面试返回的code
    private $codeMap = [
        'buildinterview' => [
            '0' => '参数错误',
            '-1' => '时间戳已过期',
            '-2' => 'token验证失败',
            '-3' => '系统类型不存在',
            '-9' => '处理失败',
            '-10' => 'json数据格式错误',
            '-99' => '未知异常',
        ],
        'cancelroom' => [
            '0' => '参数错误',
            '-1' => '时间戳已过期',
            '-2' => 'token验证失败',
            '-3' => '系统类型不存在',
            '-4' => '房间不存在',
            '-5' => '房间状态不符合取消条件',
            '-9' => '取消房间失败',
            '-99' => '未知异常',
        ],
        'canceljobseeker' => [
            '0' => '参数错误',
            '-1' => '时间戳已过期',
            '-2' => 'token验证失败',
            '-3' => '系统类型不存在',
            '-4' => '求职者不存在',
            '-5' => '求职者已连接或已结束',
            '-6' => '求职者不属于该房间',
            '-7' => '求职者不符合取消条件',
            '-9' => '取消求职者失败',
            '-99' => '未知异常',
        ],
        'addmultijobseekers' => [
            '0' => '参数错误',
            '-1' => '时间戳已过期',
            '-2' => 'token验证失败',
            '-3' => '系统类型不存在',
            '-4' => '房间不存在',
            '-5' => '面试官不存在',
            '-6' => '该房间已完成或过期',
            '-7' => '该房间已取消',
            '-8' => '房间内已安排了相同手机号的求职者',
            '-9' => '批量新增求职者失败',
            '-10' => 'json数据格式错误',
            '-11' => '面试官已完成或过期',
            '-12' => '面试官已取消',
            '-13' => '面试官与房间不匹配',
            '-99' => '未知异常',
        ],
        'addmultiinterviewers' => [
            '0' => '参数错误',
            '-1' => '时间戳已过期',
            '-2' => 'token验证失败',
            '-3' => '系统类型不存在',
            '-4' => '房间不存在',
            '-5' => '已安排了相同手机号的面试官',
            '-6' => '该房间已完成或过期',
            '-7' => '该房间已取消',
            '-9' => '批量新增面试官失败',
            '-10' => 'json数据格式错误',
            '-99' => '未知异常',
        ],
        'cancelinterviewer' => [
            '0' => '参数错误',
            '-1' => '时间戳已过期',
            '-2' => 'token验证失败',
            '-3' => '系统类型不存在',
            '-4' => '面试官不存在',
            '-5' => '面试官已连接或已结束',
            '-6' => '面试官不属于该房间',
            '-7' => '面试官已失效',
            '-9' => '取消面试官失败',
            '-99' => '未知异常',
        ],
        'updatejobseeker' => [
            '0' => '参数错误',
            '-1' => '时间戳已过期',
            '-2' => 'token验证失败',
            '-3' => '系统类型不存在',
            '-4' => '房间不存在',
            '-5' => '求职者已连接或已结束',
            '-6' => '房间已结束或过期',
            '-7' => '房间已取消或删除',
            '-8' => '求职者已取消或者已过期',
            '-9' => '修改求职者失败',
            '-10' => '房间与求职者不匹配',
            '-99' => '未知异常',
        ],
    ];


    public function __construct() {
        $options = config('extraapi.vsapi', []);
        $this->systemType = $options['systemtype'];
        $this->host = $options['host'];
        $this->key = $options['key'];
        $this->timeout = $options['timeout'];
        $this->timeStamp = time();
        $this->client = new Client([
            'base_uri' => $this->host,
            'timeout' => $this->timeout
        ]);
    }

    //生成token
    public function generateToken($argument) {
        foreach ($argument as $key => $item) {
            if (stripos($key, 'nt_') === 0 || $key == 'token') {
                unset($argument[$key]);
            }
        }
        ksort($argument);
        $string = implode('', $argument);
        return strtolower(md5(strtolower(md5($string) . $this->key)));
    }

    /**
     * Notes:创建房间
     * @param $roomInfo
     * @return array|mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function createRoom($roomInfo) {
        $func = 'createroom';
        $params = [
            'systemtype' => $this->systemType,
            'func' => $func,
            'roomname' => $roomInfo['roomname'],
            'linktype' => $roomInfo['linktype'],
            'starttime' => $roomInfo['starttime'],
            'endtime' => $roomInfo['endtime'],
            'coid' => $roomInfo['crmsubid'],
            'isjobseekerinline' => 1,
            'coname' => $roomInfo['subname'],
            'timestamp' => $this->timeStamp,
        ];
        $params['token'] = $this->generateToken($params);
        unset($params['func']);
        try {
            $response = $this->client->request('POST', '?func=' . $func, [
                'form_params' => $params,
            ])->getBody()->getContents();
            $result = json_decode($response, true);
            if ($result['result'] != 1) {
                Log::error('视频面试接口 ' . $func . ' 错误', ['params' => $params, 'result' => $result]);
                $result['message'] = $this->codeMap[$func][$result['result']] ?? '未知错误';
            }
            return $result;
        } catch (Exception $ex) {
            Log::error('视频面试接口 ' . $func . ' 错误', ['errmsg' => $ex->getMessage()]);
            return ['result' => -98, 'message' => '请求错误'];
        }
    }

    /**
     * Notes:一次安排面试 （房间、面试官、求职者）
     * @param $roomInfo
     * @return array|mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function buildInterview($roomInfo) {
        $func = 'buildinterview';
        $params = [
            'systemtype' => $this->systemType,
            'func' => $func,
            'roomname' => $roomInfo['roomname'],
            'linktype' => $roomInfo['linktype'],
            'starttime' => $roomInfo['starttime'],
            'endtime' => $roomInfo['endtime'],
            'coid' => $roomInfo['crmsubid'],
            'isjobseekerinline' => 1,
            'nt_arrangeinterviewdata' => 0,
            'coname' => $roomInfo['subname'],
            'timestamp' => $this->timeStamp,
        ];
        $params['token'] = $this->generateToken($params);
        $params['nt_arrangeinterviewdata'] = json_encode($roomInfo['interviewdata'],JSON_HEX_TAG);
        unset($params['func']);
        try {
            $response = $this->client->request('POST', '?func=' . $func, [
                'form_params' => $params,
            ])->getBody()->getContents();
            $result = json_decode($response, true);
            if ($result['result'] != 1) {
                Log::error('视频面试接口 ' . $func . ' 错误', ['params' => $params, 'result' => $result]);
                $result['message'] = $this->codeMap[$func][$result['result']] ?? '未知错误';
            }
            return $result;
        } catch (Exception $ex) {
            Log::error('视频面试接口 ' . $func . ' 错误', ['errmsg' => $ex->getMessage()]);
            return ['result' => -98, 'message' => '请求错误'];
        }
    }

    /**
     * Notes:取消房间
     * @param $vs_roomId
     * @return array|mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function cancelRoom($vs_roomId) {
        $func = 'cancelroom';
        $params = [
            'systemtype' => $this->systemType,
            'func' => $func,
            'roomid' => $vs_roomId,
            'timestamp' => $this->timeStamp,
        ];
        $params['token'] = $this->generateToken($params);
        unset($params['func']);
        try {
            $response = $this->client->request('POST', '?func=' . $func, [
                'form_params' => $params,
            ])->getBody()->getContents();
            $result = json_decode($response, true);
            if ($result['result'] != 1) {
                Log::error('视频面试接口 ' . $func . ' 错误', ['params' => $params, 'result' => $result]);
                $result['message'] = $this->codeMap[$func][$result['result']] ?? '未知错误';
            }
            return $result;
        } catch (Exception $ex) {
            Log::error('视频面试接口 ' . $func . ' 错误', ['errmsg' => $ex->getMessage()]);
            return ['result' => -98, 'message' => '请求错误'];
        }
    }

    /**
     * Notes:批量添加面试官
     * @param $vs_roomId
     * @param $interviewInfo
     * @return array|mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function batchAddInterviewer($vs_roomId, $interviewInfo) {
        $func = 'addmultiinterviewers';
        $params = [
            'systemtype' => $this->systemType,
            'func' => $func,
            'interviewroomid' => $vs_roomId,
            'timestamp' => $this->timeStamp,
        ];
        $params['token'] = $this->generateToken($params);
        $params['nt_interviewers'] = json_encode($interviewInfo, JSON_HEX_TAG);
        unset($params['func']);
        try {
            $response = $this->client->request('POST', '?func=' . $func, [
                'form_params' => $params,
            ])->getBody()->getContents();
            $result = json_decode($response, true);
            if ($result['result'] != 1) {
                Log::error('视频面试接口 ' . $func . ' 错误', ['params' => $params, 'result' => $result]);
                $result['message'] = $this->codeMap[$func][$result['result']] ?? '未知错误';
            }
            return $result;
        } catch (Exception $ex) {
            Log::error('视频面试接口 ' . $func . ' 错误', ['errmsg' => $ex->getMessage()]);
            return ['result' => -98, 'message' => '请求错误'];
        }
    }

    /**删除面试官
     * Notes:
     * @param $vs_roomId
     * @param $vs_interviewerId
     * @return array|mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function delInterviewer($vs_roomId, $vs_interviewerId) {
        $func = 'cancelinterviewer';
        $params = [
            'systemtype' => $this->systemType,
            'func' => $func,
            'interviewerid' => $vs_interviewerId,
            'interviewroomid' => $vs_roomId,
            'issendmsg' => 1,
            'timestamp' => $this->timeStamp,
        ];
        $params['token'] = $this->generateToken($params);
        unset($params['func']);
        try {
            $response = $this->client->request('POST', '?func=' . $func, [
                'form_params' => $params,
            ])->getBody()->getContents();
            $result = json_decode($response, true);
            if ($result['result'] != 1) {
                Log::error('视频面试接口 ' . $func . ' 错误', ['params' => $params, 'result' => $result]);
                $result['message'] = $this->codeMap[$func][$result['result']] ?? '未知错误';
            }
            return $result;
        } catch (Exception $ex) {
            Log::error('视频面试接口 ' . $func . ' 错误', ['errmsg' => $ex->getMessage()]);
            return ['result' => -98, 'message' => '请求错误'];
        }
    }

    /**
     * Notes:批量添加求职者
     * @param $vs_roomId
     * @param $jobseekerInfo
     * @return array|mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function batchAddJobseeker($vs_roomId, $jobseekerInfo) {
        $func = 'addmultijobseekers';
        $params = [
            'systemtype' => $this->systemType,
            'func' => $func,
            'interviewroomid' => $vs_roomId,
            'timestamp' => $this->timeStamp,
        ];
        $params['token'] = $this->generateToken($params);
        $params['nt_jobseekers'] = json_encode($jobseekerInfo, JSON_HEX_TAG);
        unset($params['func']);
        try {
            $response = $this->client->request('POST', '?func=' . $func, [
                'form_params' => $params,
            ])->getBody()->getContents();
            $result = json_decode($response, true);
            if ($result['result'] != 1) {
                Log::error('视频面试接口 ' . $func . ' 错误', ['params' => $params, 'result' => $result]);
                $result['message'] = $this->codeMap[$func][$result['result']] ?? '未知错误';
            }
            return $result;
        } catch (Exception $ex) {
            Log::error('视频面试接口 ' . $func . ' 错误', ['errmsg' => $ex->getMessage()]);
            return ['result' => -98, 'message' => '请求错误'];
        }
    }

    /**
     * Notes:修改求职者面试安排
     * @param $jobseekerInfo
     * @return array|mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function updateJobseeker($jobseekerInfo) {
        $func = 'updatejobseeker';
        $params = [
            'systemtype' => $this->systemType,
            'func' => $func,
            'jobseekerid' => $jobseekerInfo['jobseekerid_out'],
            'interviewroomid' => $jobseekerInfo['roomid_out'],
            'jobseekername' => $jobseekerInfo['cname'],
            'mobile' => $jobseekerInfo['mobilephone'],
            'email' => $jobseekerInfo['email'],
            'aid' => $jobseekerInfo['resumeid'],
            'cvlogid' => $jobseekerInfo['resumeid'],
            'autorecordvideo' => $jobseekerInfo['autorecordvideo'],
            'coid' => $jobseekerInfo['subid'],
            'coname' => $jobseekerInfo['subname'],
            'jobid' => $jobseekerInfo['caseid'],
            'jobname' => $jobseekerInfo['casename'],
            'starttime' => $jobseekerInfo['starttime'],
            'endtime' => $jobseekerInfo['endtime'],
            'timestamp' => $this->timeStamp,
        ];
        $params['token'] = $this->generateToken($params);
        unset($params['func']);
        try {
            $response = $this->client->request('POST', '?func=' . $func, [
                'form_params' => $params,
            ])->getBody()->getContents();
            $result = json_decode($response, true);
            if ($result['result'] != 1) {
                Log::error('视频面试接口 ' . $func . ' 错误', ['params' => $params, 'result' => $result]);
                $result['message'] = $this->codeMap[$func][$result['result']] ?? '未知错误';
            }
            return $result;
        } catch (Exception $ex) {
            Log::error('视频面试接口 ' . $func . ' 错误', ['errmsg' => $ex->getMessage()]);
            return ['result' => -98, 'message' => '请求错误'];
        }
    }

    /**
     * Notes:删除求职者
     * @param $vs_roomId
     * @param $vs_jobseekerId
     * @return array|mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function delJobSeeker($vs_roomId, $vs_jobseekerId) {
        $func = 'canceljobseeker';
        $params = [
            'systemtype' => $this->systemType,
            'func' => $func,
            'jobseekerid' => $vs_jobseekerId,
            'interviewroomid' => $vs_roomId,
            'timestamp' => $this->timeStamp,
        ];
        $params['token'] = $this->generateToken($params);
        unset($params['func']);
        try {
            $response = $this->client->request('POST', '?func=' . $func, [
                'form_params' => $params,
            ])->getBody()->getContents();
            $result = json_decode($response, true);
            if ($result['result'] != 1) {
                Log::error('视频面试接口 ' . $func . ' 错误', ['params' => $params, 'result' => $result]);
                $result['message'] = $this->codeMap[$func][$result['result']] ?? '未知错误';
            }
            return $result;
        } catch (Exception $ex) {
            Log::error('视频面试接口 ' . $func . ' 错误', ['errmsg' => $ex->getMessage()]);
            return ['result' => -98, 'message' => '请求错误'];
        }
    }

    public function createLinker() {

    }

    public function recordVideo() {

    }
}